package com.mezz.bones.framework.mybatis.dynamic.service;

import cn.hutool.core.util.StrUtil;
import com.mezz.bones.framework.mybatis.dynamic.enhance.EnhancedDynamicRoutingDataSource;
import com.mezz.bones.framework.mybatis.dynamic.domain.dto.DynamicDataSourceInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class DynamicDataSourceService {

    private final EnhancedDynamicRoutingDataSource dynamicRoutingDataSource;
    private final DataSourceCreatorService dataSourceCreatorService;

    public void addDataSource(DynamicDataSourceInfo dataSourceInfo) {

        if (!StringUtils.hasText(dataSourceInfo.getDatasourceKey())) {
            throw new IllegalArgumentException("Datasource datasourceKey不能为空");
        }
        // 判断数据源是否已存在
        Map<String, DataSource> currentDataSources = dynamicRoutingDataSource.getDataSources();
        if (currentDataSources.containsKey(dataSourceInfo.getDatasourceKey())) {
            //key不能重复定义
            throw new IllegalArgumentException(StrUtil.format("Datasource datasourceKey[{}]已存在，无法重复添加", dataSourceInfo.getDatasourceKey()));
        }

        dynamicRoutingDataSource.addDataSource(dataSourceInfo.getDatasourceKey(), dataSourceCreatorService.createDatasource(dataSourceInfo));
    }

    /**
     * 可能是运行状态中修改了数据库连接信息
     * 可能是运行状态中删除了数据库连接信息
     * @param datasourceKey
     */
    public void removeDataSource(String datasourceKey) {
        dynamicRoutingDataSource.removeDataSource(datasourceKey);
    }
}